<%@page contentType="text/xml;charset=UTF-8" %><?xml version="1.0" encoding="utf-8"?>
<%@ page import="java.util.Map"
%><%@ page import="java.util.TreeMap"
%><%@ page import="java.util.List"
%><%@ page import="org.apache.commons.lang.StringEscapeUtils"
%><%@ page import="org.apache.taglibs.standard.tag.common.sql.ResultImpl"
%><%@ page import="javax.servlet.jsp.JspWriter"
%><%@ page import="java.io.IOException"
%><%@ page import="java.io.FileWriter"
%><%@ page import="java.io.BufferedWriter"
%><%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"
%><%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"
%><%@ taglib uri="http://java.sun.com/jstl/sql" prefix="sql"
%><%!
TreeMap<String,String[]> meta;
TreeMap<String,String[]> langs;

BufferedWriter log = null;

int currHandle = 0;
int submitter = 0;

void initLog () {
	try {
		FileWriter logFile = new FileWriter("d:/data/dspace/elis/convelis.log");
		log = new BufferedWriter(logFile);
	} catch(IOException e) {
	}
}

void exportOne(JspWriter out, String field, String tag) throws IOException {
	if (tag==null)tag=field;
	String[] value = meta.get(field);
	if (value != null && value.length > 0) {
		out.print('<');
		out.print(tag);
		out.print('>');
		out.print(StringEscapeUtils.escapeXml(value[0]));
		out.print("</");
		out.print(tag);
		out.print('>');
		for (int i = 1; i<value.length; i++) {
			log.write(""+currHandle);
			log.write(':');
			log.write(field);
			log.write('[');
			log.write(""+i);
			log.write("]=");
			log.write(value[i]);
			log.write("\r\n");
		}
	}
}

%><sql:setDataSource driver="org.postgresql.Driver" url="jdbc:postgresql://localhost:5432/dspace-elis" user="postgres" password="googleCODE"
/><sql:query var="handles">SELECT h.handle_id as handle, i.submitter_id as submitter
  FROM handle as h, item as i
  WHERE i.item_id = h.resource_id and h.resource_type_id=2
        and i.in_archive
        and i.last_modified > '2011-01-01'
  ORDER BY handle
  LIMIT 500;
</sql:query><eprints xmlns="http://eprints.org/ep2/data/2.0"><%
	initLog();
    log.write("500 records to be exported...\r\n");
    ResultImpl handles = (org.apache.taglibs.standard.tag.common.sql.ResultImpl) pageContext.getAttribute("handles");
	for (Map<String,Object> row : handles.getRows()) {
		currHandle = (Integer)row.get("handle");
		submitter = (Integer)row.get("submitter");
		meta = new TreeMap<String,String[]>();
		langs = new TreeMap<String,String[]>();
%><eprint>
    <eprintid><%=currHandle%></eprintid><eprint_status>archive</eprint_status>
<sql:query var="item">SELECT h.handle_id as handle,
       coalesce(r.element||'_'||r.qualifier,r.element) as dcfield,
       m.place as rank,m.text_lang as lang, m.text_value as value
  FROM metadatavalue as m, metadatafieldregistry as r, handle as h, item as i
  WHERE i.item_id = h.resource_id and h.resource_type_id=2
        and m.item_id = i.item_id
        and i.in_archive
        and m.metadata_field_id = r.metadata_field_id
        and h.handle_id = <%=currHandle%>
  ORDER BY dcfield ASC, place DESC;
</sql:query><%
    ResultImpl result = (org.apache.taglibs.standard.tag.common.sql.ResultImpl) pageContext.getAttribute("item");
    String currField = "";
	String[] data = new String[0];
	String[] datlang = new String[0];
	for (Map<String,Object> rowi : result.getRows()) {
		String newField = (String)rowi.get("dcfield");
		if (!currField.equals(newField)) {
			currField = newField;
			data = new String[(Integer)rowi.get("rank")];
			datlang = new String[(Integer)rowi.get("rank")];
			if (!currField.isEmpty()) {
				meta.put(currField,data);
				langs.put(currField,datlang);
			}
		}
		data[(Integer)rowi.get("rank")-1] = (String)rowi.get("value"); 
		datlang[(Integer)rowi.get("rank")-1] = (String)rowi.get("lang"); 
	}
	String[] datestamp = meta.get("date_accessioned");
	if (datestamp != null && datestamp.length > 0) {
		%><datestamp><%=StringEscapeUtils.escapeXml(datestamp[datestamp.length-1].substring(0,10))%></datestamp>
<%
	}
	String[] eprintIds = meta.get("identifier_eprintid"); // Is this an "old" record coming back?
	String eprintId = null;
	if (eprintIds != null && eprintIds.length > 0) {
		eprintId = eprintIds[0];
		if(eprintId == null || eprintId.isEmpty()) eprintId = null;
	}
	if (submitter > 0) {
		%><userid><%=submitter%></userid><%
	}
	String[] value = meta.get("type");
	if (value != null && value.length > 0) {
		String typePub = value[0];
		if (value[0].equalsIgnoreCase("Preprint")) {typePub = "preprint"; }
		else if (value[0].equalsIgnoreCase("Thesis")) {typePub = "thesis"; }
		else if (value[0].equalsIgnoreCase("Book")) {typePub = "book"; }
		else if (value[0].equalsIgnoreCase("Book Chapter")) {typePub = "bookchapter"; }
		else if (value[0].equalsIgnoreCase("Bibliography")) {typePub = "bibliography"; }
		else if (value[0].equalsIgnoreCase("Guide/Manual")) {typePub = "guide"; }
		else if (value[0].equalsIgnoreCase("Tutorial")) {typePub = "tutorial"; } // NOT USED
		else if (value[0].equalsIgnoreCase("Library Instructional Material")) {typePub = "instrlis"; } // NOT USED
		else if (value[0].equalsIgnoreCase("Conference Proceedings")) {typePub = "proceedings"; }
		else if (value[0].equalsIgnoreCase("Conference Paper")) {typePub = "confpaper"; }
		else if (value[0].equalsIgnoreCase("Conference Poster")) {typePub = "confposter"; }
		else if (value[0].equalsIgnoreCase("Presentation")) {typePub = "presentation"; }
		else if (value[0].equalsIgnoreCase("Project/Business Plan")) {typePub = "project"; }
		else if (value[0].equalsIgnoreCase("Report")) {typePub = "report"; }
		else if (value[0].equalsIgnoreCase("Departmental Technical Report")) {typePub = "deptechreport"; } // NOT USED
		else if (value[0].equalsIgnoreCase("Technical Report")) {typePub = "techreport"; } // NOT USED
		else if (value[0].equalsIgnoreCase("Journal Article (On-line/Unpaginated)")) {typePub = "journale"; }
		else if (value[0].equalsIgnoreCase("Journal Article (Print/Paginated)")) {typePub = "journalp"; }
		else if (value[0].equalsIgnoreCase("Review")) {typePub = "review"; }
		else if (value[0].equalsIgnoreCase("Newspaper/Magazine Article")) {typePub = "newsarticle"; }
		else if (value[0].equalsIgnoreCase("In Collection")) {typePub = "incollection"; } // NOT USED
		else if (value[0].equalsIgnoreCase("Dataset")) {typePub = "dataset"; }
		else if (value[0].equalsIgnoreCase("Other")) {typePub = "other"; }
		else {
			log.write(currHandle);
			log.write(": unrecognized type=");
			log.write(typePub);
			log.write("\r\n");
		}
		%><type><%=typePub%></type><%
	}

	exportOne(out,"description_abstract","abstract");

	String[] otherdescription = meta.get("description_othersabs");
	if (otherdescription != null && otherdescription.length > 0) {
	%><othersabs>
    <item>
      <othabstracts><%=StringEscapeUtils.escapeXml(otherdescription[0])%></othabstracts>
      <language><%=langs.get("description_othersabs")[0]%></language>
    </item>
  </othersabs>
<%
	}
	exportOne(out,"relation_altloc","altloc");
	String[] authors = meta.get("contributor_author");
	if (authors != null && authors.length > 0) {
		%><creators><%
	   for (String oneAuthor: authors) {
		String family = oneAuthor;
		String given = "";
		int pv = family.indexOf(',');
		if (pv >= 0) {
			family = oneAuthor.substring(0,pv);
			given = oneAuthor.substring(pv+1).trim();	
		}
	  %><item>
	      <name>
	        <family><%=StringEscapeUtils.escapeXml(family)%></family>
	        <%if(!given.isEmpty()){%><given><%=StringEscapeUtils.escapeXml(given)%></given><%}
	      %></name>
	      <id></id>
</item><%
	  }%></creators><%
	}
	
	exportOne(out,"description_chapter","chapter");
	exportOne(out,"description_commref","commref");
	exportOne(out,"description_department","department");
	exportOne(out,"description_institution","institution");

	authors = meta.get("contributor_editor");
	if (authors != null && authors.length > 0) {
	%><editors>
<%    for (String oneAuthor: authors) {
		String family = oneAuthor;
		String given = "";
		int pv = family.indexOf(',');
		if (pv >= 0) {
			family = oneAuthor.substring(0,pv);
			given = oneAuthor.substring(pv+1).trim();	
		}
	  %><item>
	      <name>
	        <family><%=StringEscapeUtils.escapeXml(family)%></family>
	        <%if(!given.isEmpty()){%><given><%=StringEscapeUtils.escapeXml(given)%></given><%}
	      %></name>
	      <id></id>
</item><%
	  }
	%></editors>
<%	}
	exportOne(out,"relation_conferencedate","confdates");
	exportOne(out,"relation_conferencename","conference");
	exportOne(out,"relation_conferenceplace","confloc");
	String[] ispubs = meta.get("description_ispublished");
	if (ispubs != null && ispubs.length > 0) {
		String ispub = ispubs[0];
		if (ispub.equalsIgnoreCase("Published")) { ispub="pub"; }
		else if (ispub.equalsIgnoreCase("Unpublished")) { ispub="unpub"; }
		else if (ispub.equalsIgnoreCase("In Press")) { ispub="inpress"; }
		 %><ispublished><%=ispub%></ispublished><%
	}
	exportOne(out,"subject_keywords","keywords");

	String[] languages = meta.get("language_iso");
	if (languages != null && languages.length > 0) {
	%><linguabib>
<%    for (String oneLang: languages) {
	  %><item><%=StringEscapeUtils.escapeXml(oneLang)%></item><%
	  }
	%></linguabib>
<%	}

	exportOne(out,"relation_number","number");

	String pagerange = "";
	String[] firstpage = meta.get("relation_firstpage");
	if (firstpage != null && firstpage.length > 0) {
		pagerange = firstpage[0];
	}
	String[] lastpage = meta.get("relation_lastpage");
	if (lastpage != null && lastpage.length > 0) {
		if (pagerange.isEmpty()) pagerange=lastpage[0];
		else pagerange = pagerange+'-'+lastpage[0];
	}
	if (!pagerange.isEmpty()) {
		%><pagerange><%=StringEscapeUtils.escapeXml(pagerange)%></pagerange>
<%
	}

	// *** pubdom BOOLEAN = ???? ***
	exportOne(out,"relation_ispartof","publication");
	exportOne(out,"publisher",null);
	String[] refereed = meta.get("type_refereed");
	if (refereed != null && refereed.length > 0) {
		if (refereed[0].equalsIgnoreCase("Peer reviewed")) {
			%><refereed>TRUE</refereed><%
		} else {
			%><refereed>FALSE</refereed><%
		}
	}
	exportOne(out,"relation_references","referencetext");
	exportOne(out,"relation_series","series");
	exportOne(out,"relation_reportno","reportno");
		
	// *** DO WE SWITCH TO SKOS ids ??? ***
	String[] jitas = meta.get("subject_jita");
	if (jitas != null && jitas.length > 0) {
	%><subjects>
<%    for (String oneJita: jitas) {
		String family = oneJita;
		int pv = family.indexOf("::");
		if (pv >= 0) {
			family = oneJita.substring(pv+2,pv+4).trim();
			if (family.equalsIgnoreCase("ID")) {
				if (eprintId == null) {
					family = "IE";	
				}
			} else if (family.equalsIgnoreCase("IE")) {
				if (eprintId == null) {
					family = "ID";	
				}
			}
		} else {
			family = ""+oneJita.charAt(0)+'.';
		}
	  %><item><%=family%></item><%
	  }
	%></subjects>
<%	}

	// Codes missing in EPrints: AX, HK and RS
	String[] countries = meta.get("description_country");
	if (countries != null && countries.length > 0) {
	%><countries>
<%    for (String oneCountry: countries) {
	  %><item><%=oneCountry%>-</item><%
	  }
	%></countries>
<%	}

    exportOne(out,"type_thesistype","thesistype");
 	exportOne(out,"title",null);
	exportOne(out,"relation_volume","volume");
	exportOne(out,"date_issued","date");
	// *** full_text_status public
%><sql:query var="docs">
	SELECT h.handle_id as handle, bs.bitstream_id as bid, b.name as name, s.sequence_id as seq, f.mimetype as mime,
	   s.name as orig, s.size_bytes as size,  s.description as desc, s.source as source, 
       s.store_number, s.internal_id
  FROM bitstream as s, bundle2bitstream as bs, bundle as b, item2bundle as ib, item as i, handle as h, bitstreamformatregistry as f
  where s.bitstream_id = bs.bitstream_id
        and bs.bundle_id = b.bundle_id
        and b.bundle_id = ib.bundle_id
        and i.item_id = ib.item_id
        and h.resource_id = i.item_id
        and h.resource_type_id = 2
        and deleted='f'
        and f.bitstream_format_id = s.bitstream_format_id
        and handle_id = <%=currHandle%>
        and b.name = 'ORIGINAL'
  order by s.sequence_id
</sql:query><documents><%
// *** documents: pos=doc.rank, format=mime, licence=CODE, language, security, main (if one is start point),
// ***  *** within document, files: file filename, url=original url or file: local path for import
	ResultImpl dresult = (ResultImpl) pageContext.getAttribute("docs");
	for (Map<String,Object> rowi : dresult.getRows()) {
		int bid = (Integer)rowi.get("bid"); //http://eprints.rclis.org/retrieve/**bid**
		int seq = (Integer)rowi.get("seq");
		long size = (Long)rowi.get("size");
		String mime = (String)rowi.get("mime");
		String desc = (String)rowi.get("desc");
		String source = (String)rowi.get("orig");
		if (source == null) source = ""+seq;
		if (desc == null) desc = source;
		%><document id="http://eprints.rclis.org/bitstream/10760/<%=currHandle%>/<%=seq%>/<%=StringEscapeUtils.escapeXml(source)%>" xmlns="http://eprints.org/ep2/data/2.0"><docid><%=bid%></docid>
        <%--rev_number>1</rev_number><eprintid><%=currHandle%></eprintid--%><pos><%=seq%></pos>
        <format><%=mime%></format>
        <language>en</language>
        <security>public</security>
        <main><%=StringEscapeUtils.escapeXml(desc)%></main>
        <files>
          <file>
            <filename><%=StringEscapeUtils.escapeXml(source)%></filename>
            <%--filesize><%=size%></filesize--%><url>http://eprints.rclis.org/bitstream/10760/<%=currHandle%>/<%=seq%>/<%=StringEscapeUtils.escapeXml(source)%></url>
          </file>
        </files>
      </document><%
      }
    %></documents></eprint>
<%
	}
	log.close();
%></eprints>
